package cj.web.admin.controllers;

import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.constants.CategoryEnum;
import cj.web.admin.constants.DownloadTypeEnum;
import cj.web.admin.dao.DownloadDAO;
import cj.web.admin.domain.Downloading;
import cj.web.login.controllers.BaseController;

@Path("/download")
public class DownloadController extends BaseController{

	private static Logger logger = Logger.getLogger(DownloadController.class.getName());
	
	@Autowired
	private DownloadDAO downloadDao;

	@Get("query")
	public String query(Model model,Downloading newRanking)
	{
		downloadDao.query(newRanking);
		return null;
	}
	
	@Get("queryById")
	public String queryById(Model model,@Param("id") String id)
	{
		downloadDao.queryById(id);
		return null;
	}
	
	@Get("show")
	public String show(Model model){		
		EnumSet<DownloadTypeEnum> typeEnum = EnumSet.allOf(DownloadTypeEnum.class);
		model.add("typeEnum", typeEnum);
		
		return "/views/portal/downloadList.vm";
	}
	
	@Post("getList")
	public String getList(Downloading newRanking){
		JSONObject jo = new JSONObject();
		
		List<Downloading> objs = downloadDao.getList(newRanking);	
				
		int size = downloadDao.getSize(newRanking);
		
		jo.put("data", objs);
		jo.put("draw", newRanking.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model)
	{
		EnumSet<DownloadTypeEnum> typeEnum = EnumSet.allOf(DownloadTypeEnum.class);
		model.add("typeEnum", typeEnum);
		return "/views/portal/downloadDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,Downloading newRanking,@Param("uploadfile") MultipartFile file,@Param("uploadimage") MultipartFile image,HttpServletRequest request) throws IllegalStateException, IOException
	{
		
		newRanking.setId(ReturnUUID.getUUID());
		newRanking.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		newRanking.setCreateAT(DateUtils.getNowTime());
		newRanking.setCreateUser(returnSessionObj(request).getAccount());
		newRanking.setUpdateAT(DateUtils.getNowTime());
		newRanking.setUpdateUser(returnSessionObj(request).getAccount());
		
		String path = uploadfile(file, request);
		
		if(path != null &&path.length() > 0){
			newRanking.setUpFile(path);
		}		
		
		String imagePath = uploadImage(image, request);
		
		if(imagePath != null &&imagePath.length() > 0){
			newRanking.setCarouselImage(imagePath);
		}
		
		downloadDao.create(newRanking);
		
		return "r:show";
	}

	
	
	@Get("edit")
	public String edit(Model model,@Param("id") String id)
	{
		EnumSet<DownloadTypeEnum> typeEnum = EnumSet.allOf(DownloadTypeEnum.class);
		model.add("typeEnum", typeEnum);
		
		Downloading obj = downloadDao.queryById(id);
		model.add("newRanking", obj);
		return "/views/portal/downloadEdit.vm";
	}
	
	@Post("update")
	public String update(Model model, Downloading newRanking, @Param("uploadfile") MultipartFile file,
			@Param("uploadimage") MultipartFile image, HttpServletRequest request) throws Exception {

		newRanking.setUpdateAT(DateUtils.getNowTime());
		newRanking.setUpdateUser(returnSessionObj(request).getAccount());

		String path = uploadfile(file, request);

		if (path != null && path.length() > 0) {
			newRanking.setUpFile(path);
		}

		String imagePath = uploadImage(image, request);

		if (imagePath != null && imagePath.length() > 0) {
			newRanking.setCarouselImage(imagePath);
		}

		downloadDao.update(newRanking);
		
		return "r:show";

	}
	
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") String id)
	{
		downloadDao.deleteById(id);
		return "r:show";
	}
	
	@Get("fileDelete")
    public String fileDelete(@Param("key") String key) {
		JSONObject jo = new JSONObject();
		jo.put("key", key);
		jo.put("id", key);
		return "@"+jo.toString();
	}
	
	private String uploadImage(MultipartFile image, HttpServletRequest request) throws IOException {
		String filePath = "";
		
		if(image != null && !image.isEmpty()){
			// 文件保存路径  
        	String path = ReadConfigProperties.getValue("uploadFilePath") + "/upload";
        	//判断文件是否存在，不存在创建文件
        	Map rep = ReturnUUID.getFolder(path);
        	path = rep.get("allpath").toString();//所在的全路径
        	//文件名
            String fileName =  ReturnUUID.getName(image.getOriginalFilename()); 
            // 转存文件  
            image.transferTo(new File(path + "/" +fileName)); 
            
            ImageUtils.scale2(path+"/"+fileName, path+"/"+fileName+".thumb.jpg", 300, 300, false);//缩率图
            
            filePath = "/upload/"+rep.get("filepath")+"/"+fileName;
		}
		
		return filePath;
	}

	private String uploadfile(MultipartFile file, HttpServletRequest request) throws IOException {
		String filePath = "";
		
		if(file != null && !file.isEmpty()){
			// 文件保存路径  
        	String path = ReadConfigProperties.getValue("uploadFilePath") + "/upload";
        	//判断文件是否存在，不存在创建文件
        	Map rep = ReturnUUID.getFolder(path);
        	path = rep.get("allpath").toString();//所在的全路径
        	//文件名
            String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
            // 转存文件  
            file.transferTo(new File(path + "/" +fileName)); 
            
            filePath = "/upload/" + rep.get("filepath").toString() + "/" + fileName;
                        
		}
		
		return filePath;
	}
	
}
